#include "game.h"
#include "widget.h"
#include "core.h"
#include "log.h"

game::game()
{
	m_render = core::get_inst().get_render();
}

game::~game()
{
	widget* wg = *(m_renderlist.begin());
	if(wg)
		wg->hide();
	map<const char*,widget*>::iterator m_it;
	for(m_it=m_widgets.begin();m_it!=m_widgets.end();m_it++)
	{
		((*m_it).second)->destroy();
		delete (*m_it).second;
	}
	m_widgets.clear();
}

void game::add_widget(widget* _wid,const char* _name)
{
	m_widgets[_name]=_wid;
	m_widgets[_name]->create();
}

void game::set_widget(const char* _name)
{
	widget* wg;
	if(m_renderlist.size()>0)
	{
		wg = *(m_renderlist.begin());
		if(wg)
			wg->hide();
	}
	m_renderlist.clear();
	m_updatelist.clear();
	wg = m_widgets[_name];
	if(!wg)
	{
		LOG_FATAL("Widget %s not found.",_name);
	}
	m_renderlist.push_front(wg);
	m_updatelist.push_front(wg);
	wg->show();
}

void game::update(u32 _dt)
{
	widget* wg = *(m_updatelist.begin());
	wg->update(_dt);
}

void game::draw()
{
	widget* wg = *(m_renderlist.begin());
	wg->draw();
}

void game::event_keyboard(u32 _type,u32 _key)
{
	if(m_updatelist.size())
	{
		widget* wg = *(m_updatelist.begin());
		wg->event_keyboard(_type,_key);
	}
}

void game::event_mouse(u32 _type,u32 _x,u32 _y,u32 _keys)
{
	if(m_updatelist.size())
	{
		widget* wg = *(m_updatelist.begin());
		wg->event_mouse(_type,_x,_y,_keys);
	}
}